package utils

import (
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"net/smtp"
	"strings"
)

func SendMail(lastName, firstName, EmailAddr, phoneNumber, organization, desc string, mails []string) (err error) {
	mailConf := EmailConfInit()
	receiver := mails[0]
	CcAddress := ""
	if len(mails) > 1 {
		CcSlice := mails[1:]
		CcAddress = strings.Join(CcSlice, ";")
	} else if len(mails) == 1 {
		CcAddress = receiver
 	} else {
		err = fmt.Errorf("没找到能接收邮件的email地址，请查看是否已添加后台管理邮箱。")
		return err
	}
	message := []byte("To:" + receiver + "\r\n" +
		"From:" + mailConf.User + "\r\n" +
		"Cc:" + CcAddress + "\r\n" +
		fmt.Sprintf("Subject:新用户%s先生/女士\r\n", lastName) +
		"\r\n" +
		"您好，有新用户提交信息，请查收！\r\n\n" +
		fmt.Sprintf("联系人：%s \r\n", lastName+firstName) +
		fmt.Sprintf("电话：%s \r\n", phoneNumber) +
		fmt.Sprintf("邮箱：%s \r\n", EmailAddr) +
		fmt.Sprintf("组织机构：%s \r\n", organization) +
		fmt.Sprintf("描述信息：%s.\r\n", desc))
	mailAddress := fmt.Sprintf("%s:%d", mailConf.Host, mailConf.Port)
	auth := smtp.PlainAuth("", mailConf.User, mailConf.Password, mailConf.Host)
	if err := SendMailUsingTLS(mailAddress, auth, mailConf.User, mails, message); err != nil {
		return err
	}
	log.Println("邮件发送成功!")
	return
}

func Dial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil)
	if err != nil {
		log.Println("Dialing Error:", err)
		return nil, err
	}
	//分解主机端口字符串
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}

func SendMailUsingTLS(addr string, auth smtp.Auth, from string,
	to []string, msg []byte) (err error) {
	//create smtp client
	c, err := Dial(addr)
	if err != nil {
		log.Println("Create smpt client error:", err)
		return err
	}
	defer c.Close()
	if auth != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(auth); err != nil {
				log.Println("Error during AUTH", err)
				return err
			}
		}
	}
	if err = c.Mail(from); err != nil {
		return err
	}
	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return err
		}
	}
	w, err := c.Data()
	if err != nil {
		return err
	}
	_, err = w.Write(msg)
	if err != nil {
		return err
	}
	err = w.Close()
	if err != nil {
		return err
	}
	return c.Quit()
}
